/**
 * BookUI.java
 * FlightBookingCentre
 * Phillip
 * 2014��3��22�� ����2:04:36
 */
package com.view.client;

import com.controller.client.RMIClient;
import com.dao.Flight;
import com.util.Constant;
import com.util.Printer;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.rmi.RemoteException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Phillip
 */
public class BookUI extends JFrame {

    String[] classItems = {"ECO", "BUS", "FIR"};
    private RMIClient client;
    private List<Flight> flights;

    private JLabel myJLabel;
    private JLabel nameJLabel;
    private JLabel phoneJLabel;
    private JLabel emailJLabel;
    private JLabel creditJLabel;
    private JLabel textJLabel;
    private JLabel departJLabel;
    private JLabel returnjLabel;
    private JLabel priceJLabel;

    private JTextField nameJTextField;
    private JTextField phoneJTextField;
    private JTextField emailJTextField;
    private JTextField creditJTextField;

    private JComboBox<String> class1;
    private JComboBox<String> class2;
    private JButton confirmJButton;

    public BookUI(final RMIClient client, final List<Flight> flights) {
        this.client = client;
        this.flights = flights;
        Printer.p(flights.get(0).getFligthNOString());
        Printer.p(flights.get(1).getFligthNOString());
        Printer.p(flights.get(0).getPriceString());
        Printer.p(flights.get(1).getPriceString());
        int totalPrice = Integer.parseInt(flights.get(0).getPriceString()) + Integer.parseInt(flights.get(1).getPriceString());

        this.setTitle("MY FLIGHT BOOKING CENTRE");
        this.setLayout(new GridBagLayout());
        this.setSize(300, 500);
        this.setResizable(false);

        myJLabel = new JLabel("Please input your personal information:");
        nameJLabel = new JLabel("Name");
        phoneJLabel = new JLabel("Mobile");
        emailJLabel = new JLabel("E-mail");
        creditJLabel = new JLabel("Credit");
        textJLabel = new JLabel("Please choose the seat class you want:");
        departJLabel = new JLabel("depart");
        returnjLabel = new JLabel("return");
        priceJLabel = new JLabel("total price is " + totalPrice + " RMB");

        class1 = new JComboBox<String>(classItems);
        class2 = new JComboBox<String>(classItems);

        class1.addItemListener(new ItemListener() {

            String newPrice1 = "";
            String newPrice2 = "";

            @Override
            public void itemStateChanged(ItemEvent arg0) {

                String classString1 = arg0.getItem().toString();
                String classString2 = class2.getSelectedItem().toString();
                Printer.p(classString2);

                flights.get(0).setClassEnum(classString1);
                try {
                    switch (flights.get(0).getAirlineString()) {
                        case "Air China":
                            newPrice1 = client.queryRates(1,flights.get(0).getFligthNOString(), classString1);
                            newPrice2 = client.queryRates(1,flights.get(1).getFligthNOString(), classString2);

                            Printer.p(newPrice1 + " " + newPrice2);
                            break;
                        case "Qantas":
                            newPrice1 = client.queryRates(2, flights.get(0).getFligthNOString(), classString1);
                            newPrice2 = client.queryRates(2, flights.get(1).getFligthNOString(), classString2);
                            break;
                        default:
                            break;
                    }
                } catch (RemoteException e) {
                    //undone
                }


                try {
                    priceJLabel.setText("total price is " + (Integer.parseInt(newPrice1) + Integer.parseInt(newPrice2)) + " RMB");
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(null, "Connection Error!", "Error", JOptionPane.ERROR_MESSAGE);
                    dispose();
                }
            }
        });

        class2.addItemListener(new ItemListener() {

            String newPrice1 = "";
            String newPrice2 = "";

            @Override
            public void itemStateChanged(ItemEvent arg0) {

                String classString2 = arg0.getItem().toString();
                String classString1 = class1.getSelectedItem().toString();

                flights.get(1).setClassEnum(classString2);

                try {
                    switch (flights.get(0).getAirlineString()) {
                        case "Air China":
                            newPrice1 = client.queryRates(1, flights.get(0).getFligthNOString(), classString1);
                            newPrice2 = client.queryRates(1, flights.get(1).getFligthNOString(), classString2);

                            Printer.p(newPrice1 + " " + newPrice2);
                            break;
                        case "Qantas":
                            newPrice1 = client.queryRates(2, flights.get(0).getFligthNOString(), classString1);
                            newPrice2 = client.queryRates(2, flights.get(1).getFligthNOString(), classString2);
                            break;
                        default:
                            break;
                    }
                } catch (RemoteException e) {
                    //undone
                }


                try {
                    priceJLabel.setText("total price is " + (Integer.parseInt(newPrice1) + Integer.parseInt(newPrice2)) + " RMB");
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(null, "Connection Error!", "Error", JOptionPane.ERROR_MESSAGE);
                    dispose();
                }

            }
        });

        nameJTextField = new JTextField(10);
        // nameJTextField.setText("HuYifei");
        phoneJTextField = new JTextField(10);
        // phoneJTextField.setText("18021245594");
        emailJTextField = new JTextField(10);
        // emailJTextField.setText("jsxhhyf@gmail.com");
        creditJTextField = new JTextField(10);
        // creditJTextField.setText("0123456789012345");

        confirmJButton = new JButton("Confirm!");
        confirmJButton.addActionListener(new confirmButtonHandler());

        GridBagConstraints c = new GridBagConstraints();

        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 2;
        c.anchor = GridBagConstraints.LINE_START;
        c.insets = new Insets(10, 10, 10, 10);
        this.add(textJLabel, c);

        c.gridy = 1;
        c.gridwidth = 1;
        this.add(departJLabel, c);

        c.gridx = 1;
        this.add(returnjLabel, c);

        c.gridx = 0;
        c.gridy = 2;
        c.insets = new Insets(0, 10, 10, 10);
        this.add(class1, c);

        c.gridx = 1;
        this.add(class2, c);

        c.gridx = 0;
        c.gridy = 3;
        c.gridwidth = 2;
        c.insets = new Insets(10, 10, 10, 10);
        this.add(priceJLabel, c);

        c.fill = GridBagConstraints.BOTH;
        c.gridy = 4;
        this.add(myJLabel, c);

        c.gridy = 5;
        c.gridwidth = 1;
        this.add(nameJLabel, c);

        c.gridx = 1;
        this.add(nameJTextField, c);

        c.gridx = 0;
        c.gridy = 6;
        this.add(creditJLabel, c);

        c.gridx = 1;
        this.add(creditJTextField, c);

        c.gridx = 0;
        c.gridy = 7;
        this.add(phoneJLabel, c);

        c.gridx = 1;
        this.add(phoneJTextField, c);

        c.gridx = 0;
        c.gridy = 8;
        this.add(emailJLabel, c);

        c.gridx = 1;
        this.add(emailJTextField, c);

        c.gridx = 0;
        c.gridy = 9;
        c.gridwidth = 2;
        this.add(confirmJButton, c);

        this.setVisible(true);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

    public boolean validateInfo() {
        Pattern namePattern = Pattern.compile("^\\w+$");
        Pattern emailPattern = Pattern.compile("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$");
        Pattern phonePattern = Pattern.compile("[0-9]{11}");
        Pattern creditPattern = Pattern.compile("[0-9]{16}");

        Matcher nameMatcher = namePattern.matcher(nameJTextField.getText());
        Matcher emailMatcher = emailPattern.matcher(emailJTextField.getText());
        Matcher phoneMatcher = phonePattern.matcher(phoneJTextField.getText());
        Matcher creditMatcher = creditPattern.matcher(creditJTextField.getText());

        if (!nameMatcher.matches()) {
            JOptionPane.showMessageDialog(null, "Please input the right format of Name!", "Error", JOptionPane.ERROR_MESSAGE);
            return false;
        } else if (!emailMatcher.matches()) {
            JOptionPane.showMessageDialog(null, "Please input the right format of Email!", "Error", JOptionPane.ERROR_MESSAGE);
            return false;
        } else if (!phoneMatcher.matches()) {
            JOptionPane.showMessageDialog(null, "Please input the right format of phone number (11 digits)!", "Error", JOptionPane.ERROR_MESSAGE);
            return false;
        } else if (!creditMatcher.matches()) {
            JOptionPane.showMessageDialog(null, "Please input the right format of credit number (16 digits)!", "Error", JOptionPane.ERROR_MESSAGE);
            return false;
        } else {
            return true;
        }

    }

    private class confirmButtonHandler implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            String bookResultString = "";
            Flight flight1 = flights.get(0);
            Flight flight2 = flights.get(1);
            String airlineString = flight1.getAirlineString();


            if (!validateInfo()) {
                return;
            }
            try {
                switch (airlineString) {
                    case "Air China":
                        bookResultString = client.book(1, flight1.getFligthNOString(), "TODO", class1.getSelectedItem()
                                .toString(), flight2.getFligthNOString(), "TODO", class2.getSelectedItem().toString(), nameJTextField
                                .getText(), creditJTextField.getText());
                        break;
                    case "Qantas":
                        bookResultString = client.book(2, flight1.getFligthNOString(), "TODO", class1.getSelectedItem()
                                .toString(), flight2.getFligthNOString(), "TODO", class2.getSelectedItem().toString(), nameJTextField
                                .getText(), creditJTextField.getText());
                        break;

                    default:
                        break;
                }
            } catch (RemoteException e1) {
                //undone
            }


            Printer.p(bookResultString);
            switch (bookResultString) {
                case Constant.DUPLICATETICKETS_STRING:
                    JOptionPane.showMessageDialog(null, "You have already book a seat in this flight!", "Error", JOptionPane.ERROR_MESSAGE);
                    break;
                case Constant.NODEPTSEAT_STRING:
                    JOptionPane.showMessageDialog(null, "No available seats in departure flight!", "Error", JOptionPane.ERROR_MESSAGE);
                    break;
                case Constant.NORETURNSEAT_STRING:
                    JOptionPane.showMessageDialog(null, "No available seats in return flight!", "Error", JOptionPane.ERROR_MESSAGE);
                    break;
                case Constant.BOOKFAILED_STRING:
                    JOptionPane.showMessageDialog(null, "Book failed!", "Error", JOptionPane.ERROR_MESSAGE);
                    break;
                case Constant.BOOKSUCCESSFUL_STRING:
                    new ResultUI(flights);
                    dispose();
                    break;
                default:
                    JOptionPane.showMessageDialog(null, bookResultString, "Error", JOptionPane.ERROR_MESSAGE);
                    break;
            }
        }

    }
}
